<?php

namespace common\behavior\CommonMessagePushing;

use common\model\EntityModel;
use common\model\TaskModel;
use common\model\UserModel;
use common\service\BehaviorService;
use common\service\OptionsService;
use common\service\TaskAssembleService;
use common\service\TaskAssignService;
use common\service\TaskService;
use common\service\TaskUpstreamService;
use Webman\Stomp\Client;

/**
 * 任务分配至部门行为 消息通知
 */
class TaskAssignToDepartmentBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'assign_user' => 'intval',
                'assign_result' => '',
            ],
            [
                'assign_user' => 0,
                'assign_result' => [],
            ],
            'data',
            ['type' => 'task_assign_to_department'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($assignUserId, $assignResult) = $params;
        if (empty($assignUserId) || empty($assignResult)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/
        $departmentIdList = [];
        $taskIdList = [];
        foreach ($assignResult as $departmentId => $stepCategoryAssignResult) {
            $departmentIdList[] = $departmentId;
            foreach ($stepCategoryAssignResult as $stepCategoryId => $taskAssignResultList) {
                $taskIdList = array_merge($taskIdList, $taskAssignResultList);
            }
        }
        if (empty($taskIdList)) {
            return;
        }
        // 任务没有执行人的才通知
        $taskWithoutExecutor = model(TaskModel::class)
            ->where([
                'id' => ['in', $taskIdList],
                'executor' => 0
            ])
            ->field('id,plan_end_time,project_id')
            ->select();
        if (empty($taskWithoutExecutor)) {
            return;
        }
        // 部门组长
        $users = teamones_request('teamones-im', 'tenant/select_tenant_user', [
            'param' => [
                'filter' => [
                    'department.id' => ['-in', implode(',', $departmentIdList)],
                    'role.code' => TaskService::HEADMAN_CODE
                ],
            ]
        ])['data'];
        $remoteUserData = [];
        foreach ($users as $user) {
            foreach ($user['department_info'] as $department) {
                $remoteUserData[$department['id']][] = $user;
            }
        }
        $assignUser = model(UserModel::class)->find($assignUserId);
        $notifyMessages = [];

        foreach ($assignResult as $departmentId => $taskStepCategoryList) {

            $currentHeadmanUserList = $remoteUserData[$departmentId] ?? [];
            if (count($currentHeadmanUserList) === 0) {
                continue;
            }
            $taskIdList = array_merge(...array_values($taskStepCategoryList));
            $taskList = array_filter($taskWithoutExecutor, fn($item) => in_array($item['id'], $taskIdList));
            if (empty($taskList)) {
                continue;
            }
            $subTaskEndTime = array_column($taskList, 'plan_end_time');
            $notifyParam = [
                'first' => "新到了一批任务",
                'remark' => "请及时分配任务",
                'assign_username' => $assignUser['name'],
                'assign_time' => date("Y/m/d H:i"),
            ];
            $notifyParam['task_number'] = count($taskIdList);
            $notifyParam['task_start_time'] = date("Y/m/d H:i", min($subTaskEndTime));
            $notifyParam['task_end_time'] = date("Y/m/d H:i", max($subTaskEndTime));
            foreach ($currentHeadmanUserList as $headmanUser) {
                $notifyMessages[] = [
                    'param' => $notifyParam,
                    'receiver' => $headmanUser['user_id'],
                    'project_id' => $taskList[0]['project_id'],
                ];
            }
        }

        $messageGenerated = [];
        $templateId = TaskAssignService::getInstance()->getSetTaskExecutorMessageTemplateId();
        foreach ($notifyMessages as $message) {
            $messageGenerated[] = [
                "param" => $message['param'],
                'receiver' => $message['receiver'],
                'template_id' => $templateId,
                'content_type' => 'card_message',
                'notice_type' => 'message_task',
                'is_popup' => 1,
                'message_key' => 'step_category_task_assignee',
                'project_id' => $message['project_id'],
            ];
        }

        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
